<?php
class Admins extends MY_Controller 
{
	var $curl = 'admins';
	var $name = '';
	var $search = '';
	var $per_page = 0;
	var $language;
	var $id_admin = '';
	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model(array('/public/admin_model', '/public/acl_role_model'));

		$this->validation->set_fields($this->admin_model->fields);
		
		$this->data['Title'] = T_('Administrators');
		
		$this->name = T_('Administrators');
		
		$this->data['login_form'] = 'agent/login';
		$this->data['login_error'] = '';
		$this->data['forgot_error'] = '';
		$this->data['forgot_completed'] = '';
		$this->validation->forgot_user_email = '';
		$this->validation->forgot_user_login = '';

		$this->language = parent::getLang();		
	}
	
	function index()
	{
		$this->admin_model->search();		
		$this->renderLayout();
	}

	function create()
	{
		// Get User Roles
		//$this->data['roles'] = $this->acl_role_model->getSelectOptions();
		//$id_roles = $this->input->post('id_roles');
		//$this->data['user_roles'] = (!empty($id_roles) ? $id_roles : array());
		$this->data['role'] = $this->auth->getUserData('role');
		
		if (count($_POST))
		{
			$rules = array('first_name', 'last_name', 'email', 'password', 'password_confirm', 'status');
			if ($this->data['role'] == USER_ROLE_SUPERADMIN)
			{
				array_push($rules, 'id_acl_roles');
			}
			
			$this->validation->set_rules($this->admin_model->getRules($rules));
			
			$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("Administrator").'»</span> '.T_("already exists with such email. Please change the email."));
			
			if ($this->validation->run() === TRUE)
			{
				$item['password'] 	= $this->validation->password;
				$item['first_name']	= $this->validation->first_name;
				$item['last_name']	= $this->validation->last_name;
				$item['email'] 		= $this->validation->email;
				$item['status'] 	= $this->validation->status;
				$item['activation_code']= md5(rand(1, 1000000) . time() . SALT);
				$item['id_acl_roles'] = ($this->auth->getUserData('role') == USER_ROLE_SUPERADMIN) ? $this->validation->id_acl_roles : ROLE_ADMIN;
	
				if ($this->admin_model->insert($item))
				{
					/*
					$data_user = $item;
					$data_user['email_name'] = EMAIL_REGISTER_ADMIN;
			        $link = $this->config->item('site_url') . $this->config->item('base_url') .'admins/activation/'.$data_user['activation_code'];
			        $data_user['activation_link'] = '<a href="'.$link.'">'.$link.'</a>';

			        $result = sendEmail($data_user);

					$this->log->writeMessage('done', T_('Email with link activation has sent to you.'));
					*/
					redirect($this->curl . '/index');	
				}		
			}
		}
		
		$this->renderLayout();			
	}
	
	function edit($id = null)
	{
		if (!empty($id))
		{
			if (($this->auth->getUserData('role') != USER_ROLE_SUPERADMIN) && ($id != $this->auth->getID()))
			{
				redirect('/admins/prohibited_page');
			}
			
			$object = $this->admin_model->get($id);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
			
			// Get User Roles
			//$this->data['roles'] = $this->acl_role_model->getSelectOptions();
			//$this->data['user_roles'] = $this->acl_role_model->getUserRoles($id, ADMIN_GROUP_ID);
			$this->data['role'] = $this->auth->getUserData('role');
			
			if (!count($_POST))
			{
				$this->validation->id 			= $object['id'];
				$this->validation->first_name 	= $object['first_name'];
				$this->validation->last_name 	= $object['last_name'];  
				$this->validation->email 		= $object['email'];
				$this->validation->status 		= $object['status'];
				$this->validation->id_acl_roles = $object['id_acl_roles'];		 
			}
			else
			{
				$this->id_admin = $id;
				
				$rules = array('first_name', 'last_name', 'email', 'status');
				if ($this->data['role'] == USER_ROLE_SUPERADMIN)
				{
					array_push($rules, 'id_acl_roles');
				}
				
				$this->validation->set_rules($this->admin_model->getRules($rules));
	
				$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("Administrator").'»</span> '.T_("already exists with such email. Please change the email."));
				
				if ($this->validation->run() === TRUE)
				{	
					$item['id'] 		= $this->validation->id;
					//$item['password'] = $this->validation->password;
					$item['first_name'] = $this->validation->first_name;
					$item['last_name'] 	= $this->validation->last_name;
					$item['email'] 		= $this->validation->email;
					$item['status'] 	= $this->validation->status;
					$item['id_acl_roles'] = ($this->auth->getUserData('role') == 'Superadmin') ? $this->validation->id_acl_roles : ROLE_ADMIN;
					
					$this->admin_model->update($item);
					
					redirect($this->curl . '/index');
				}
			}
		}
	
		$this->renderLayout();
	}

	function deleteItems()
	{
		$data = $this->admin_model->delete($_REQUEST['items']);

		echo $data;
	}

	function delete($id)
	{
		$data = $this->admin_model->delete($id);

		if ($data)
		{
			redirect($this->curl . '/index');	
		}
		else
		{
			redirect($this->curl . '/edit/'. $id);
		}		
	}

	function activity()
	{
		$data = $this->utils->publishItems($this->admin_model->table, $this->admin_model->prKey, $this->admin_model->publishedField, $_REQUEST['items'], $_REQUEST['action']);
		echo $this->utils->php2js($data);
	}
		
	function __loginFree($login = null)
	{		
		return $this->admin_model->loginFree($login);
	}
	
	function login($forgot_completed = null)
	{
		if (isset($_POST['enter']))
		{
			if ($user = $this->admin_model->getByLoginPassword($this->input->post('user_login'), $this->input->post('user_password')))
			{
				if ($user['status'] == USER_STATUS_ACTIVE)
				{
					$this->auth->login($user);
					
					redirect('homepage/index');
				}
				else
				{
					$this->data['login_error'] = '<p class="msg error">'.T_('Your account has blocked.').'</p>';
				}
			}
			else
			{				
				$this->data['login_error'] = '<p class="msg error">'.T_('Incorrect login or password.').'</p>';
			}			
		}
		
		$this->data['forgot_completed'] = $forgot_completed;
		$this->data['forgot_error'] = '';
		$this->layout 	= 'login';
		$this->view 	= $this->curl . '/login';
		$this->data['hide_menu'] = true;
		$this->data['Title'] = 'HN Books Admin';						
		$this->renderLayout();
	}
	
	function password_forgot()
	{
		if (count($_POST))
		{
			$this->admin_model->rules =	array(
											'forgot_user_login' => "trim|required|valid_email|max_length[64]"
										);
			$rules = array('forgot_user_login');
			$this->validation->set_rules($this->admin_model->getRules($rules));

			if ($this->validation->run() === TRUE)
			{							
				if ($user = $this->admin_model->getByLogin($this->input->post('forgot_user_login')))
				{
					if ($user['status'] == USER_STATUS_ACTIVE)
					{
						$new_password = humanPassword(6);
						$subject = "New password";
	     				$item['id'] = $user['id'];
	    				$item['activation_code'] = $this->admin_model->__cryptPassword($new_password);
	    				$message = "Hello ".$user['fullname'].".<br />									 
								    Your new password: $new_password 
	     						    <a target='_blank' href='".$this->config->item('site_url') . $this->config->item('base_url')."admins/reset_password/".$item['activation_code']."'>".$this->config->item('site_url') . $this->config->item('base_url')."admins/reset_password/".$item['activation_code']."</a>.\n\r
	    							You may change the password after authorisation.<br /> 
	     
	    							Sincerely,<br />
									Website Administration."; 
						//$item['date_modified'] = date('Y-m-d H:i:s');
						$sql = 'UPDATE '.$this->admin_model->table.' SET activation_code='.$this->db->escape($item['activation_code']).' WHERE id='.$item['id'];						
						
						$this->db->query($sql);

						$this->load->library('email');	
						$config['mailtype'] = 'html';
						$config['protocol'] = 'mail';
						$config['charset'] = 'utf-8';
						$config['newline'] = '\r\n';
	
						$this->email->initialize($config);
						$this->email->from($this->config->item('site_email'), EMAIL_FROM_NAME);
						$this->email->to($user['email']);					
						$this->email->subject($subject);
						$this->email->message($message);												
						$this->email->send();
						
						//echo $this->email->print_debugger();
						
						redirect($this->curl . '/login/forgot_completed');
					}
					else
					{
						$this->data['forgot_error'] = $this->validation->_error_prefix . T_('Your account has blocked.') . $this->validation->_error_suffix;
					}
				}
				else
				{
					$this->data['forgot_error'] = $this->validation->_error_prefix . T_('Incorrect login.') . $this->validation->_error_suffix;
				}
			}
			else
			{
				$this->data['forgot_error'] = $this->validation->error_string;
			}			
		}

		$this->data['login_error'] = '';
		$this->layout 	= 'login';
		$this->view 	= $this->curl . '/login';
		$this->data['hide_menu'] = true;
		$this->renderLayout();
	}
		
	function reset_password($code = null)
	{
		if (!empty($code))
		{
			if ($this->admin_model->resetPasswordUser($code))
			{
				$this->log->writeMessage('done', T_('Ваш пароль изменён. Можете войти в систему, используя свой логин и новый пароль, высланный Вам ранее на почту.'));
				
				redirect('/');
			}
			else
			{				
				$this->log->writeMessage('error', T_('The Password has not changed.'));
				redirect('/'); 
			}			
		}
		
		$this->data['Title'] = 'Password Recovery';
								
		$this->renderLayout();
	}
		
	function logout()
	{
		$this->auth->logout();
		
		redirect('admins/login');
	}
	
	function details()
	{
		$id = $this->auth->getID();

		if (!empty($id))
		{
			$object = $this->admin_model->get($id);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
			
			if (!count($_POST))
			{
				$this->validation->id 			= $object['id']; 
				$this->validation->first_name 	= $object['first_name']; 
				$this->validation->last_name 	= $object['last_name']; 
				$this->validation->email 		= $object['email'];
				$this->validation->password 	= '';
				$this->validation->password_confirm = '';				
				$this->validation->status 		= $object['status'];		 
			}
			else
			{
				$this->id_admin = $id;
				
				$rules = array('new_password', 'password_confirm', 'first_name', 'last_name', 'email', 'status');
				$this->validation->set_rules($this->admin_model->getRules($rules));

				//$this->validation->set_message('__loginFree', '<span class="black bold">«Admin»</span> already exists with such email.');

				if ($this->validation->run() === TRUE)
				{
					
					$item['id'] 		= $this->validation->id;
					$item['first_name'] = $this->validation->first_name;
					$item['last_name']  = $this->validation->last_name;
					$item['email'] 		= $this->validation->email;
					$item['status'] 	= $this->validation->status;

					if (!empty($this->validation->password))
					{
						$item['password'] 	= $this->validation->password;
					}
						
					$this->admin_model->update($item);
					$data = $this->auth->getUserData();
					$data['first_name'] = $item['first_name'];
					$data['last_name'] 	= $item['last_name'];
					$data['fullname'] 	= $item['first_name'] . ' ' . $item['last_name'];
					$data['email'] 		= $item['email'];
					$data['status'] 	= $item['status'];
					$this->auth->setUserData($data);
					
					$this->log->writeMessage('done', T_('Saved succesfully.'));
					
					redirect('/');
				}
			}	
		}

		$this->data['Title'] .= ' / ' . T_('My Settings');
		$this->view 	= 'admins/details';
		$this->renderLayout();
	}	
	
	function prohibited_page()
	{
		$this->layout 	= 'login';
		$this->view 	= 'admins/prohibited_page';
		$this->data['hide_menu'] = true;
		$this->renderLayout();
	}	
	
	function activation($code = null)
	{
		if (!empty($code))
		{
			if ($this->admin_model->activateUser($code))
			{
				$this->log->writeMessage('done', T_('Your account has actived. You may enter the system using your login and password.'));
				
				redirect('/');
			}
			else
			{				
				$this->log->writeMessage('error', T_('Account has not actived.'));
			}			
		}
		
		$this->data['Title'] = 'Account Activation';
								
		$this->renderLayout();
	}
}
?>